/**
 * Created by liuqingxia on 2016/4/8.
 */

/**
 * 组装node的Text
 * @param userName
 * @param jdbcUrl
 * @returns {string}
 */
function dataSourceName(userName, jdbcUrl) {

    var nodeText = userName + "@";

    if (jdbcUrl.contains("DESCRIPTION")) {/*oracle的RAC格式*/
        return nodeText + HandleOracleRACName(jdbcUrl);
    }

    var removeQuestMark = jdbcUrl.split("?")[0];
    if (!containsIP(removeQuestMark) && removeQuestMark.contains("@")) {
        return nodeText + removeQuestMark.split("@")[1];
    }

    if (!containsIP(removeQuestMark) && removeQuestMark.contains("mysql://")) {
        return nodeText + removeQuestMark.split("mysql://")[1];
    }
    
    if (removeQuestMark.contains("jdbc:sqlserver://")) {
    	return nodeText + removeQuestMark.split("jdbc:sqlserver://")[1];
    }

    var ipPortDbReg = /\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}:\d{1,6}(\/|\:)\w+/;

    var ipPortDb = $.trim(ipPortDbReg.exec(removeQuestMark)).split(",")[0];

    nodeText += ipPortDb;

    return nodeText;
}

/**
 * 字符串中是否包含ip地址
 * @param str
 * @returns {boolean}
 */
function containsIP(str) {
    var ipReg = /(\d+)\.(\d+)\.(\d+)\.(\d+)/;//正则表达式
    return ipReg.test(str);
}

/**
 * 提取oracle的rac格式的jdbc连接
 * @param jdbcUrl
 * @returns {string}
 */
function HandleOracleRACName(jdbcUrl) {
    var ip = $.trim(jdbcUrl.split("HOST")[1].split("=")[1].split(")")[0]);

    var port = $.trim(jdbcUrl.split("PORT")[1].split("=")[1].split(")")[0]);

    var dbName = $.trim(jdbcUrl.split("SERVICE_NAME")[1].split("=")[1].split(")")[0]);

    return ip + ":" + port + "/" + dbName;
}

var sourceTypes = ["drds", "mysql", "oracle","sqlserver"];//数据源类型

/**
 * 显示数据源选择Tree
 * @param type
 * @param divId
 */
function showDataSourceTree(type, divId, buttons) {
    var container = $("#" + divId);
    if (isNull(type)) {
        return;
    }
    type = $.trim(type);
    if (existSourceType(type)) {
        container.empty();
        showOneTypeDataSource(divId, type, buttons);
        container.show();
    }
}

/**
 * 是否是存在的数据源类型
 * @param type
 * @returns {boolean}
 */
function existSourceType(type) {
    if (sourceTypes.indexOf($.trim(type)) != -1) {
        return true;
    } else {
        return false;
    }
}


/**
 * 根据dataSource的id获取tableName的数组
 * @param sourceId
 * @returns {Array}
 */
function getTableNames(sourceId) {
    var tableArr = [];
    var params = {};
    params['id'] = sourceId;
    $.postHttpSync(params, getUrlBySuffix("/datasource/getTables"), function (json) {
        if (json && json.success) {
            tableArr = json['list'];
        }
    })
    return tableArr;
}

/**
 * 根据tableName数组，生成tableNameSelect
 * @param tableArr
 * @param selectId
 * @returns {string}
 */
function genTableNameSelect(tableNameArr, selectId) {

    var tableNameOptions = "";

    for (var index in tableNameArr) {

        var tableName = tableNameArr[index];

        tableNameOptions += "<option value='" + tableName + "'>" +
            tableName +
            "</option>";
    }

    var tableNameSelect = "" +
        "<select class='selectpicker bs-select-hidden' style='width: 400px'" +
        "id='" + selectId + "'> " +
        tableNameOptions +
        "</select>";

    return tableNameSelect;
}


/**
 * * 返回可视化的tableNameUi
 * @param tableNameArr
 * @param tableNameLiClass
 * @param tableNameSelectButtonId
 * @returns {string}
 */
function genVisualTableNameUi(tableNameArr, tableNameLiClass, tableNameUiButtonId) {

    var firstTableName = tableNameArr[0];

    var tableNameLis = "";

    for (var index in tableNameArr) {
        tableNameLis += "<li data-original-index='" + index + "' " +
            "class='selected " + tableNameLiClass + "'>" +
            "<a tabindex='" + index + "' class='' style='' data-tokens='null'>" +
            "<span class='text'>" + tableNameArr[index] + "</span>" +
            "<span class='glyphicon glyphicon-ok check-mark'></span>" +
            "</a>" +
            "</li>";
    }

    var tableNameUl = "" +
        "<div class='btn-group bootstrap-select open'> " +
        "<button id='" + tableNameUiButtonId + "' " +
        "type='button' class='btn dropdown-toggle btn-default' style='width: 380px' " +
        "data-toggle='dropdown' " +
        "title='" + firstTableName + "'aria-expanded='true'> " +
        "<span class='filter-option pull-left'>" +
        firstTableName +
        "</span>&nbsp; " +
        "<span class='caret'></span> " +
        "</button>" +
        "<div class='dropdown-menu open' " +
        "style='max-height: 690.365px; overflow: hidden; min-height: 92px;'> " +
        "<ul class='dropdown-menu inner' role='menu' " +
        "style='max-height: 690.365px; overflow-y: auto; min-height: 92px;'>" +
        tableNameLis +
        "</ul>" +
        "</div>" +
        "</div>";

    return tableNameUl;
}

/**
 * 展示TableNameSelect
 * @param params
 */
function showTableNameSelect(params) {

    var sourceId = params['sourceId'];
    var visualContainerId = params['visualContainerId'];
    var tableNameLiClass = params['tableNameLiClass'];
    var tableNameUiButtonId = params['tableNameUiButtonId'];

    var tableNameArr = getTableNames(sourceId);

    var visualContainer = $("#" + visualContainerId);
    var tableNameUi = genVisualTableNameUi(tableNameArr, tableNameLiClass, tableNameUiButtonId);
    visualContainer.empty();
    visualContainer.append(tableNameUi);

}

/**
 *
 注册点击TableNameLi事件
 *
 @param readerOrWriter
 */
function clickTableNameLi(direction, tableNameUiBtnId) {

    $(document).on("click", "." + direction + "TableNameLi", function () {

        var tableName = $.trim($(this).find("span.text").html());

        var tableNameUiBtn = $("#" + tableNameUiBtnId);
        tableNameUiBtn.attr("title", tableName);

        var titleSpan = tableNameUiBtn.find("span.filter-option");
        titleSpan.empty();
        titleSpan.append(tableName);
    });

}